package com.qfjy.controller;

import com.qfjy.entity.po.User;
import com.qfjy.entity.vo.UserVO;
import com.qfjy.service.UserService;
import com.qfjy.util.excel.ExcelUtils;
import com.qfjy.util.redis.RedisRepeatUtils;
import com.qfjy.util.resulst.ResultCode;
import com.qfjy.util.resulst.ResultJson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName UserController
 * @Description TODO
 * @Author guoweixin
 * @Date 2023/5/24
 * @Version 1.0
 */
@Controller
@Slf4j
@RequestMapping("user")
@Api(tags = {"用户管理模块"})
public class UserController {

    /**Redis解决高并发 重复提交工具类*/
    @Autowired
    private RedisRepeatUtils redisRepeatUtils;

    @Autowired
    public UserService userService;

    @GetMapping("list")
    @ResponseBody
    @ApiOperation(value = "查询所有的用户列表数据")
    public ResultJson list(){

        List<User> list= userService.selectList();

        return new ResultJson(list, ResultCode.SUCCESS);
    }


    /**
     * TODO 进入用户列表页面
     */
    @GetMapping("listPage")
    public String listPage(HttpServletRequest request){

        List<User> list= userService.selectList();
        request.setAttribute("list",list);
        return "user/list";
    }

    /**
     * TODO 进入用户列表页面  列表按条件进行查询
     */
    @GetMapping("listCondition")
    @ApiOperation(value = "列表按条件进行查询")
    public String listCondition(HttpServletRequest request, UserVO userVO){

       List<User> list= userService.listCondition(userVO);

       request.setAttribute("name",userVO.getName());
       request.setAttribute("rid",userVO.getRid());
       request.setAttribute("startTime",userVO.getStartTime());
       request.setAttribute("endTime",userVO.getEndTime());
        request.setAttribute("list",list);
        return "user/list";

    }




    /**
     * TODO 进入Excel数据导入页面
     */
    @GetMapping("importExcelToPage")
    public String importExcelToPage(HttpServletRequest request){
        //生成redis token
       redisRepeatUtils.generatorToken(request,"token:importExcel");

        return "user/ImportExcel";
    }

    /**
     * TODO  Excel文件导入
     */
    @PostMapping("importExcel")
    @ResponseBody
    public ResultJson importExcel(@RequestParam("file-2")MultipartFile file,HttpServletRequest request){
        int num=0;

        //校验 redis token
       boolean flag= redisRepeatUtils.validateToken(request,"token:importExcel");
        if(flag==false){
            log.info("本次是重复提交，后台不执行业务逻辑");
            return new ResultJson(num,ResultCode.TOO_FREQUENT);
        }


        try {
            //解析Excel 工具类 解析导入
            List<User> list= ExcelUtils.importExcel(file,User.class);

            //批量添加到MYSQL数据库
             num=userService.insertBatch(list);
            log.info("导入成功：{}",list);
            Thread.sleep(500);
            return new ResultJson(num,ResultCode.SUCCESS);
        } catch (IOException e) {
            log.error("Excel导入异常"+e.getMessage());
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }


        return new ResultJson(num,ResultCode.FAIL);
    }


    /**
     * TODO 导出功能 Excel（根据列表查询的条件后）
     */
    @RequestMapping("exportExcelCondition")
    public void exportExcelCondition(HttpServletRequest request, UserVO userVO,
                                     HttpServletResponse response) throws IOException {

       List<User> list=userService.listCondition(userVO);

       ExcelUtils.exportExcel(list,"智慧会议用户信息列表","用户信息列表",User.class,"智慧会议用户信息列表",response);

    }




    /**
     * TODO 单行删除
     */
    @PostMapping("deleteById")
    @ResponseBody
    public ResultJson deleteById(@RequestParam("id")final Integer id){

       int num= userService.deleteById(id);
        log.info("根据ID进行删除:{}",num);
        return new ResultJson(num,ResultCode.SUCCESS);
    }

    /**
     * TODO 批量删除
     */
    @PostMapping("deleteBatch")
    @ResponseBody
    public ResultJson deleteBatch(@RequestParam("idsStr")String idsStr){

       String[] ids= idsStr.split(",");

        //String[] ids
       int num= userService.deleteBatch(ids);
        if(num>0){
            log.info("批量删除成功{}",num);
            return new ResultJson(num,ResultCode.SUCCESS);
        }
        return new ResultJson(num,ResultCode.FAIL);
    }

    /**
     * TODO 更改状态（有效/无效）
     *
     * @param status 状态数值
     * @param id     主值
     * @return
     */
    @GetMapping("updateStatusById")
    @ResponseBody
    public ResultJson updateStatusById(@RequestParam("status") int status,
                                       @RequestParam("id") int id){

        int num=userService.updateUserStatusById(status, id);
        return  new ResultJson(num,ResultCode.SUCCESS);
    }


}
